
// main.js import 会进入这里找routes 这个文件太多内容 可以分担给routers.js 再从routers.js 引入
import Vue from 'vue'
import VueRouter from 'vue-router';
import Main from  '../components/main.vue';
import LoginForm from '../components/flask-login.vue';
import store from '@/store';
import axios from 'axios';
import { get_cluster_name_list,get_namespace_name_list,get_es_name_list } from '@/api'
// import {post} from '@/api'
import { Message } from "view-design";

Vue.use(VueRouter);

// 解决多次点击 路由重复 bug
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err);
};

const routes = [
    {
        path: '/login',
        name: 'login',
        component: LoginForm,
        meta: {
            isLogin: true,
            title: '登录'
        }
    },
    {
        path: '/',
        name: '_home',
        redirect: '/home',
        component: Main,
        children: [
            {
                path: '/home',
                name: 'home',
                component: resolve=>{require(['@/components/post/postList'],resolve);},
                meta: {
                    isLogin: true,
                    title: '首页'
                },
            },
            {
                path: '/siteManage',
                name: 'siteManage',
                meta:{
                    title:'站点链接',
                },
                component:resolve=>{require(['@/components/site/siteManage'],resolve);}
            },

            {
                path: '/pressureSetting',
                name: 'pressureSetting',
                meta:{
                    title:'压测配置',
                },
                component:resolve=>{require(['@/components/pressure/pressureSetting'],resolve);}
            },
            {
                path: '/pressureSettingDetail',
                name: 'pressureSettingDetail',
                meta:{
                    title:'压测配置详情',
                },
                component:resolve=>{require(['@/components/pressure/pressureSettingDetail'],resolve);}
            },
            {
                path: '/pressureData',
                name: 'pressureData',
                meta:{
                    title:'压测数据',
                },
                component:resolve=>{require(['@/components/pressure/pressureData'],resolve);}
            },
            {
                path: '/pressureDataDetail',
                name: 'pressureDataDetail',
                meta:{
                    title:'压测数据详情',
                },
                component:resolve=>{require(['@/components/pressure/pressureDataDetail'],resolve);}
            },
            {
                path: '/test',
                name: 'test',
                component: () =>import ('@/components/test/myPost.vue'),
                meta: {
                    title:'前端测试页面'
                },
            },
            {
                path: '/postAdd',
                name: 'postAdd',
                component: () =>import ('@/components/post/postAdd.vue'),
                meta: {
                    requireAuth: true,  
                    title:'添加笔记'
                },
            },
            {
                path: '/postEdit',
                name: 'postEdit',
                meta: {
                    title:'编辑笔记'
                },
                component: () =>import ('@/components/post/postEdit.vue'),
            },
            {
                path: '/postList',
                name: 'postList',
                meta: {
                    title:'笔记列表'
                },
                component: () =>import ('@/components/post/postList.vue'),
            },
            {
                path: '/postDetail',
                name: 'postDetail',
                meta: {
                    title:'笔记详情'
                },
                component: () =>import ('@/components/post/postDetail.vue'),
            },

            {
                path: '/k8s/cluster/apiTest',
                name: 'apiTest',
                meta: {
                    k8s: true,
                    title:'api测试'
                },
                component: resolve=>{require(['@/components/k8s/cluster/apiTest'],resolve);},
            },
            {
                path: '/redis/dashboard',
                name: 'redisDashboard',
                meta: {
                    title:'redis大盘'
                },
                component: resolve=>{require(['@/components/redis/dashboard'],resolve);},
            },
        ]
    },
    // CMDB
    {
        path: '/cmdb',
        name: 'cmdb',
        meta:{
            title: '资产管理'
        },
        component: Main,
        children:[
            {
                path: '/server',
                name: 'server',
                component:resolve=>{require(['@/components/cmdb/server'],resolve);}
            },
            {
                path: '/webssh',
                name: 'webssh',
                component:resolve=>{require(['@/components/cmdb/webssh'],resolve);}
            },
            {
                path: '/record',
                name: 'record',
                component:resolve=>{require(['@/components/cmdb/record'],resolve);}
            },
            {
                path: '/updateLog',
                name: 'updateLog',
                component:resolve=>{require(['@/components/cmdb/updateLog'],resolve);}
            },
            {
                path: '/initLog',
                name: 'initLog',
                component:resolve=>{require(['@/components/cmdb/initLog'],resolve);}
            },
            {
                path: '/serverUser',
                name: 'serverUser',
                component:resolve=>{require(['@/components/cmdb/serverUser'],resolve);}
            },  
            {
                path: '/aliyun/accountTransactions',
                name: 'accountTransactions',
                component: resolve=>{require(['@/components/cmdb/aliyun/accountTransactions'],resolve);},
            },
            {
                path: '/aliyun/ServerList',
                name: 'aliyunServerList',
                component: resolve=>{require(['@/components/cmdb/aliyun/serverList'],resolve);},
            },
        ]

    },
    //项目管理
    {
        path: '/project',
        name: 'project',
        meta:{
            title: '项目管理'
        },
        component: Main,
        children:[
            {
                path: '/projectList',
                name: 'projectList',
                meta:{
                    title: '项目列表'
                },
                component: resolve=>{require(['@/components/project/project'],resolve);},
            }, 
            {
                path: '/env',
                name: 'env',
                meta:{
                    title: '环境管理'
                },
                component: resolve=>{require(['@/components/project/env'],resolve);},
            },  
        ]

    },
    //任务管理
    {
        path: '/task',
        name: 'task',
        meta:{
            title: '任务管理'
        },
        component: Main,
        children:[
            {
                path: '/taskList',
                name: 'taskList',
                meta:{
                    title: '任务列表'
                },
                component: resolve=>{require(['@/components/task/taskList'],resolve);},
            }, 
            {
                path: '/taskLog',
                name: 'taskLog',
                meta:{
                    title: '任务日志'
                },
                component: resolve=>{require(['@/components/task/taskLog'],resolve);},
            }, 
        ]

    },
    //系统配置
    {
        path: '/setting',
        name: 'setting',
        meta:{
            title: '系统配置'
        },
        component: Main,
        children:[
            {
                path: '/globalSetting',
                name: 'globalSetting',
                meta:{
                    title: '全局设置'
                },
                component: resolve=>{require(['@/components/setting/globalSetting'],resolve);},
            }, 
            {
                path: '/menu',
                name: 'menu',
                meta:{
                    title: '菜单管理'
                },
                component: resolve=>{require(['@/components/setting/menu'],resolve);},
            }, 
            {
                path: '/userRole',
                name: 'userRole',
                meta:{
                    title: '角色管理'
                },
                component: resolve=>{require(['@/components/setting/userRole'],resolve);},
            }, 
            {
                path: '/user',
                name: 'user',
                meta:{
                    title: '用户管理'
                },
                component: resolve=>{require(['@/components/setting/user'],resolve);},
            }, 
        ]

    },
    //日志监控
    {
        path: '/monitor',
        name: 'monitor',
        meta:{
            title: '日志监控'
        },
        component: Main,
        children:[
            // es集群
            {
                path: '/es/index',
                name: 'esIndex',
                meta: {
                    es: true,
                    title: 'ES索引'
                },
                component: resolve=>{require(['@/components/es/index'],resolve);},
            },
            {
                path: '/es/dashboard',
                name: 'esDashboard',
                meta: {
                    es: true,
                    title: 'ES大盘'
                },
                component: resolve=>{require(['@/components/es/dashboard'],resolve);},
            },
        ]
    },
    //k8s集群
    {
        path: '/k8s/cluster',
        name: 'k8sCluster',
        meta:{
            title: 'k8s集群'
        },
        component: Main,
        children:[
            {
                path: '/createCluster',
                name: 'createCluster',
                meta:{
                    title:'创建k8s集群'
                },
                component:resolve=>{require(['@/components/k8s/cluster/createCluster'],resolve);}
            },
            {
                path: '/clusterList',
                name: 'clusterList',
                meta:{
                    title:'k8s集群列表'
                },
                component:resolve=>{require(['@/components/k8s/cluster/clusterList'],resolve);}
            },
            {
                path: '/clusterStat',
                name: 'clusterStat',
                meta: {
                    k8s: true,
                    title:'k8s集群统计'
                },
                component: resolve=>{require(['@/components/k8s/cluster/clusterStat'],resolve);},
            },
            {
                path: '/nodeStat',
                name: 'nodeStat',
                meta: {
                    k8s: true,
                    title:'k8s节点统计'
                },
                component: resolve=>{require(['@/components/k8s/cluster/nodeStat'],resolve);},
            },
            {
                path: '/nodeManage',
                name: 'nodeManage',
                meta: {
                    k8s: true,
                    title:'k8s节点管理'
                },
                component: resolve=>{require(['@/components/k8s/cluster/nodeManage'],resolve);},
            },
            {
                path: '/eventList',
                name: 'eventList',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'k8s事件列表'
                },
                component: resolve=>{require(['@/components/k8s/cluster/eventList'],resolve);},
            },
            {
                path: '/createNamespace',
                name: 'createNamespace',
                meta:{
                    title:'创建命名空间'
                },
                component: resolve=>{require(['@/components/k8s/cluster/createNamespace'],resolve);},
            }, 
            {
                path: '/namespace',
                name: 'namespace',
                meta: {
                    k8s: true,
                    meta:{
                        title:'命名空间列表'
                    },
                },
                component: resolve=>{require(['@/components/k8s/cluster/namespace'],resolve);},
            }, 
            {
                path: '/namespaceStat',
                name: 'namespaceStat',
                meta: {
                    k8s: true,
                    meta:{
                        title:'命名空间统计'
                    },
                },
                component: resolve=>{require(['@/components/k8s/cluster/namespaceStat'],resolve);},
            }, 
        ]

    },
    // k8s存储
    {
        path: '/k8s/storage',
        name: 'k8sStorage',
        meta:{
            title: 'k8s存储'
        },
        component: Main,
        children:[
            {
                path: '/storageClass',
                name: 'storageClass',
                meta: {
                    k8s: true,
                    title:'存储类'
                },
                component: resolve=>{require(['@/components/k8s/storage/storageClass'],resolve);},
            }, 
            {
                path: '/pv',
                name: 'pv',
                meta: {
                    k8s: true,
                    title:'持久卷',
                },
                component: resolve=>{require(['@/components/k8s/storage/pv'],resolve);},
            }, 
            {
                path: '/pvc',
                name: 'pvc',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'持久卷声明',
                },
                component: resolve=>{require(['@/components/k8s/storage/pvc'],resolve);},
            }, 
        ]
    },
    //k8s配置
    {
        path: '/k8s/config',
        name: 'k8sConfig',
        meta:{
            title: 'k8s配置'
        },
        component: Main,
        children:[
            {
                path: '/configMap',
                name: 'configMap',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'配置列表',
                },
                component: resolve=>{require(['@/components/k8s/config/configMap'],resolve);},
            }, 
            {
                path: '/configMapDetail',
                name: 'configMapDetail',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'配置详情',
                },
                component: resolve=>{require(['@/components/k8s/config/configMapDetail'],resolve);},
            }, 
            {
                path: '/secret',
                name: 'secret',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'secret列表',
                },
                component: resolve=>{require(['@/components/k8s/config/secret'],resolve);},
            }, 
            {
                path: '/secretDetail',
                name: 'secretDetail',
                meta:{
                    title: 'secret详情'
                },
                component: resolve=>{require(['@/components/k8s/config/secretDetail'],resolve);},
            }, 
        ]
    },
    //istio网格
    {
        path: '/k8s/istio',
        name: 'k8sIstio',
        meta:{
            title: 'istio网格'
        },
        component: Main,
        children:[
            {
                path: '/gateway',
                name: 'gateway',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'istio网关',
                },
                component: resolve=>{require(['@/components/k8s/istio/gateway'],resolve);},
            }, 
            {
                path: '/virtualService',
                name: 'virtualService',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'istio虚服务',
                },
                component: resolve=>{require(['@/components/k8s/istio/virtualService'],resolve);},
            }, 
            {
                path: '/virtualServiceDetail',
                name: 'virtualServiceDetail',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'istio虚服务详情',
                },
                component: resolve=>{require(['@/components/k8s/istio/virtualServiceDetail'],resolve);},
            }, 
            {
                path: '/destinationRule',
                name: 'destinationRule',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'istio路由规则',
                },
                component: resolve=>{require(['@/components/k8s/istio/destinationRule'],resolve);},
            }, 
        ]
    },
    //k8s服务暴露
    {
        path: '/k8s/service',
        name: 'k8sService',
        meta:{
            title: 'k8s服务暴露'
        },
        component: Main,
        children:[
            {
                path: '/ingress',
                name: 'ingress',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'ingress列表'
                },
                component: resolve=>{require(['@/components/k8s/service/ingress'],resolve);},
            }, 
            {
                path: '/service',
                name: 'service',
                meta: {
                    k8s: true,
                    namespace: true,
                    title:'service列表'
                },
                component: resolve=>{require(['@/components/k8s/service/service'],resolve);},
            }, 
        ]
    },
    //k8s工作负载
    {
        path: '/k8s/workload',
        name: 'k8sWorkload',
        meta: {
            title: 'k8s工作负载'
        },
        component: Main,
        children:[
            {
                path: '/deployment',
                name: 'deployment',
                meta: {
                    k8s: true,
                    namespace: true,
                    title: 'deployment列表'
                },
                // component: resolve=>{require(['@/components/k8s/workload/deployment'],resolve);},
                component: resolve => { require(['@/components/k8s/workload/deployment/index'], resolve); },
            }, 
            {
                path: '/deploymentDetail',
                name: 'deploymentDetail',
                meta:{
                    title: 'deployment详情'
                },
                component: resolve=>{require(['@/components/k8s/workload/deployment/detail'],resolve);},
            }, 
            {
                path: '/pod',
                name: 'pod',
                meta: {
                    k8s: true,
                    namespace: true,
                    title: 'pod列表',
                },
                component: resolve=>{require(['@/components/k8s/workload/pod'],resolve);},
            }, 
            {
                path: '/podStat',
                name: 'podStat',
                meta: {
                    k8s: true,
                    title: 'pod统计',
                },
                component: resolve=>{require(['@/components/k8s/workload/podStat'],resolve);},
            }, 
            {
                path: '/podDetail',
                name: 'podDetail',
                meta: {
                    title: 'pod详情',
                },
                component: resolve=>{require(['@/components/k8s/workload/podDetail'],resolve);},
            }, 
            {
                path: '/podLog',
                name: 'podLog',
                meta: {
                    title: 'pod日志',
                },
                component: resolve=>{require(['@/components/k8s/workload/podLog'],resolve);},
            }, 
            {
                path: '/hpa',
                name: 'hpa',
                meta: {
                    k8s: true,
                    namespace: true,
                    meta:{
                        title: "弹性伸缩"
                    },
                },
                component: resolve=>{require(['@/components/k8s/workload/hpa'],resolve);},
            }, 
            {
                path: '/daemonSet',
                name: 'daemonSet',
                meta: {
                    k8s: true,
                    namespace: true,
                    title: "守护应用"
                },
                component: resolve=>{require(['@/components/k8s/workload/daemonSet'],resolve);},
            }, 
            {
                path: '/statefulSet',
                name: 'statefulSet',
                meta: {
                    k8s: true,
                    namespace: true,
                    title: "有状态应用"
                },
                component: resolve=>{require(['@/components/k8s/workload/statefulSet'],resolve);},
            }, 
            {
                path: '/statefulSetDetail',
                name: 'statefulSetDetail',
                meta:{
                    title: "有状态应用详情"
                },
                component: resolve=>{require(['@/components/k8s/workload/statefulSetDetail'],resolve);},
            }, 
        ]
    },
    //ceph
    {
        path: '/ceph',
        name: 'ceph',
        meta:{
            title: 'ceph'
        },
        component: Main,
        children:[
            {
                path: '/bucket/list',
                name: 'bucketList',
                meta:{
                    title: '桶管理'
                },
                component: resolve=>{require(['@/components/ceph/bucket'],resolve);},
            }, 
            {
                path: '/bucket/object/list',
                name: 'bucketObjectList',
                meta:{
                    title: '桶对象管理'
                },
                component: resolve=>{require(['@/components/ceph/bucketObjectList'],resolve);},
            }, 
        ]
    },
    //k8s权限
    {
        path: '/k8s/auth',
        name: 'k8sAuth',
        meta:{
            title: 'k8s权限'
        },
        component: Main,
        children:[
            // auth 
            {
                path: '/serviceAccount',
                name: 'serviceAccount',
                meta: {
                    // 页面属于k8s集群资源，并且是命名空间资源
                    k8s: true,
                    namespace: true,
                },
                component:resolve=>{require(['@/components/k8s/auth/serviceAccount'],resolve);}
            },
        ]

    },
]

const router = new VueRouter({
    routes,
    // mode: 'history'
})

function initCluster() {
    console.log("集群初始化")
    axios({
        url:get_cluster_name_list,method:'post'
    }).then( (response) => {
        if(response.status == 200){
            let  cluster_list = response.data;
            if(cluster_list == null) {
                Message.error('k8s集群连接不上，获取不到集群信息')
            }else{
                if(cluster_list.length > 0){
                    store.setClusterList(cluster_list)
                    let currentCluster =localStorage.getItem('currentCluster')
                    if(currentCluster){
                        console.log("重置集群选择项:",currentCluster)
                        store.setClusterName(currentCluster)
                    }else{
                        store.setClusterName(cluster_list[0])
                        localStorage.setItem('currentCluster',cluster_list[0])
                    }
                    return true
                }
            } 
        }else{
            console.log(JSON.stringify(response.data))
            Message.error("请先在集群管理=>集群信息=>创建集群下配置k8s集群，错误信息:"+JSON.stringify(response.data))
        }

    }).catch( error=> {
        console.log("请先在集群管理=>集群信息=>创建集群下配置k8s集群，错误信息:"+JSON.stringify(error))
        Message.error("请先在集群管理=>集群信息=>创建集群下配置k8s集群，错误信息:"+JSON.stringify(error))
    })
    return false
}


function initNamesSpace() {
    console.log("命名空间初始化")
    let currentCluster = localStorage.getItem('currentCluster')
    if (currentCluster == '' || currentCluster==null) return
    let headers = {'cluster_name':currentCluster}
    axios({
        url:get_namespace_name_list,headers: headers,method:'post'
    }).then( (response) => {
        if(response.status == 200){
            let  namespace_list = response.data;
            if(namespace_list == null) {
                Message.error('获取不到命名空间信息')
            }else{
                if(namespace_list.length > 0){
                    store.setNamespaceList(namespace_list)
    
                    let currentNameSpace = localStorage.getItem('currentNameSpace')
                    if(currentNameSpace){
                        console.log("重置命名空间选择项:",currentNameSpace)
                        store.setNamespace(currentNameSpace)
                    }else{
                        localStorage.setItem('currentNameSpace',namespace_list[0])
                        store.setNamespace(namespace_list[0])
                    }
                    return true
                }
            }
        }else{
            console.log(JSON.stringify(response.data))
            Message.error("获取不到集群的命名空间列表")
        }

    }).catch( error=> {
        console.log(JSON.stringify(error))
        Message.error("命名空间初始化失败")
    })
    return false
}
function init_cluster_ns(to){
    if(to.meta.k8s  &&  store.state.clusterList.length == 0){
        initCluster()
    }
    if(to.meta.namespace && store.state.namespaceList.length == 0){
        initNamesSpace()
    } 
}

// 
function init_es(){
    if(store.state.esClusterList.length == 0) {
        axios({
            url:get_es_name_list,method:'post',timeout:5000,
        }).then( (response) => {
            if(response.status == 200){
                let  cluster_list = response.data;
                if(cluster_list == null) {
                    Message.error('获取es集群信息失败')
                }else{
                    if(cluster_list.length > 0){
                        store.setEsClusterList(cluster_list)
                        let currentEsCluster =localStorage.getItem('currentEsCluster')
                        if(currentEsCluster){
                            console.log("重置es集群选择项:",currentEsCluster)
                            store.setEsClusterName(currentEsCluster)
                        }else{
                            store.setEsClusterName(cluster_list[0])
                            localStorage.setItem('currentEsCluster',cluster_list[0])
                        }
                        return true
                    }
                } 
            }else{
                console.log(JSON.stringify(response.data))
                Message.error("请先配置好es集群，错误信息:"+JSON.stringify(response.data))
            }
    
        }).catch( error=> {
            console.log("请先配置好es集群，错误信息:"+JSON.stringify(error))
            Message.error("请先配置好es集群，错误信息:"+JSON.stringify(error))
        })
        return false 
    }
}



router.beforeEach((to,from,next) => {
    // bug死循环，堆栈溢出
    // console.log("路由名字:"+to.name+" 路由地址:"+to.path)
    if(to.meta.requireAuth){
        if(localStorage.getItem('token')){
            if(to.meta.k8s){
                init_cluster_ns(to)
                next()
            }else if (to.meta.es){
                init_es()
                next()
            }else{
                next()
            }
        }else{
            next('/login')
        }
    }else {
        if(to.meta.k8s){
            init_cluster_ns(to)
            next()
        }else if (to.meta.es){
            init_es()
            next()  
        }else{
            next()
        }
    }
})

// router.beforeEach((to,from,next) => {
//     // bug死循环，堆栈溢出
//     // console.log("路由名字:"+to.name+" 路由地址:"+to.path)
//     if(to.meta.requireAuth){
//         if(localStorage.getItem('token')){
//             init_cluster_ns(to)
//             next()
//         }else{
//             next('/login')
//         }
//     }else {
//         init_cluster_ns(to)
//         next()
//     }
// })


export default router